<?php
/**
 * 视图基类
 * @author andery <andery@foxmail.com>
 * @link http://www.minophp.com/
 * @version $Id: CView.php 2010-02-21 00:54:45Z andery $
 */
class CView
{
    // 模板引擎对象
    private $_engine;
    // 引擎类名
    private $_className;
    // 配置信息
    private $_view_conf = array(
        'cache'=>'0',
        'tpldir'=>'template/default/',
        'objdir'=>'data/temp/compile/',
        'left_delimiter'=>'{',
        'right_deliniter'=>'}',
    );
    // 单例模式实现
    private static $_instance;
    
    /**
	 * 构造函数，初始化视图连接
     */
	public function __construct(){
	    $engineName = CConf::get('tpl.engine');
	    $engineName = empty($engineName) ? 'Nimo' : $engineName;
	    $this->_className   = 'CTemplate'.ucwords($engineName);
	    include_once(NM_PATH . '/view/' . $this->_className . '.php');
	}
	
	public static function getInstance()
	{
	    if (!(self::$_instance instanceof self)) {
	        self::$_instance = new self();
	    }
	    return self::$_instance;
	}
	
	public function set_view_config($tpl_config = ''){
	    if ($tpl_config != '') {
	        $this->_view_conf = $tpl_config;
	    }
	    $this->_engine = new $this->_className($this->_view_conf);
	}
	
	/**
	 * 显示视图
	 * @param string $tplfile 视图名
	 * @param array $tpl_data 传递给视图的变量数组
	 */
	public function display($tplfile, $tpl_data)
	{
		$site_url = Nimo::app()->getAppUrl();
	    $tpl_data['site_url'] = $site_url . '/';
	    $tpl_data['tpl_dir'] = $site_url . '/' . $this->_view_conf['tpldir'];
	    $tpl_data['memory_get_usage'] = round(memory_get_usage() / 1048576,2);
		$this->_engine->assign($tpl_data);
		ob_start();
        ob_implicit_flush(0);
		$this->_engine->display($tplfile);
		$content = ob_get_clean();
		$content = $this->_tplContentReplace($content);
		echo $content;
	}
	
	/**
	 * 设置视图变量
	 * 
	 */
	public function assign($tpl_data, $value = '')
    {
        if (!is_array($tpl_data) && $tpl_data != '') {
            $this->_engine->assign($tpl_data, $value);
        } else {
            $this->_engine->assign($tpl_data);
        }
    }
    
    /**
     * 处理模板自身处理范围外的特定作用标签
     * 
     * @access private
     * @param string $content
     * @return string
     */
    private function _tplContentReplace($content)
    {
        //表单令牌
		$content = preg_replace("/\{token (.*?)\}/eis", "\$this->_buildFormToken('\\1');", $content);
		//URL生成
		$content = preg_replace("/\{url (.*?)\}/eis", "\$this->_buildUrl('\\1');", $content);
		return $content;
    }
    
    /**
     * 表单令牌处理
     * 
     * @access private
     * @param string $name
     * @return string
     * 
     * 在令牌字符串前面加上自定义名称
     * SESSION设置为二维数组保存多个令牌
     * 可以实现多页面正常运行
     */
    private function _buildFormToken($custom_name)
    {
        if (CConf::get('token.token_on')) {
            $token_name = CConf::get('token.token_name');
            $token_type = CConf::get('token.token_type');
            $token_value = $token_type(microtime(TRUE));
            $token_value = $custom_name . '#' . $token_value;
            $token = '<input type="hidden" name="'.$token_name.'" value="'.$token_value.'" />';
            $_SESSION[$token_name][$custom_name] = $token_value;
        } else {
            $token = '';
        }
        return $token;
    }
    
    /**
     * 生成链接
     * 
     * @access private
     * @param string $url_param
     * @return string
     */
    private function _buildUrl($url_param)
    {
        $url_param = trim($url_param);
        $spit = explode('&', $url_param);
        $rute = array_shift($spit);
        $arg = array();
        foreach ($spit as $val) {
        	$val = trim($val);
            $temp_arr = explode('=', $val);
            $k = array_shift($temp_arr);
            $v = implode('=', $temp_arr);
            $arg[$k] = $v;
        }
        return $url = Nimo::app()->create_url($rute, $arg);
    }
    
    private function __clone(){}
}

